{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <link rel="stylesheet" href="{% static 'css/jquery.resizableColumns.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap-editable.css' %}">
    <link href="{% static 'bootstrap-table/css/bootstrap-table.min.css' %}" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'css/bootstrap-datepicker.min.css' %}">

<style>
    .bootstrap-table>.fixed-table-toolbar>.columns {
        margin-bottom: 10px;
    }

    .bootstrap-table>.fixed-table-toolbar>.pull-right.search {
        margin-top: -3px;
        margin-right: 5px;
    }

    .help-inline{
        width: 90%;
        word-wrap: break-word;
        word-break: break-all;
    }

    table tbody tr td, .form-static-text{
        word-wrap: break-word;
        word-break: break-all;
    }

    .error-text {
        color: #b94a48;
    }

    .has-error .selectize-input{
        border-color: #b94a48;
    }

    .children-table {
        width: 1200px !important;
    }

    .dashDiv{
        float: right;
        border: 0.5px solid #cbcbcb;
        background-color: #00C6D7;
        width: 80px;
        height: 25px;
        box-sizing: border-box;
    }
    .dashDiv .dashSpan{
        border: 0.5px solid #cbcbcb;
        background-color: #FFFFFF;
        float: right;
        width: 40px;
        height: 23px;
        box-sizing: border-box;
    }

    .dashDiv .dashSpan.converted{
        transition: .5s;
        float: left;
    }

    .form-group .disabled, .dashDiv .disabled{
        pointer-events: none;
    }

    .button-shine {
        background-image: linear-gradient(		rgba(255,255,255,0.6), 		rgba(0,0,0,0.6)	);
        display: inline-block;
        height: 25px;
        width: 50px;
        line-height: 21px;
     /*Same as height*/
        color: white;
        font-size: 12px;
        font-weight: bold;
        border-radius: 5px;
        box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
    }

    #rgb {
        background-color: #FF0;
     /*yellow*/
        animation: rgb 3s infinite alternate;
    }

    @keyframes rgb {
        /* 0% will fallback to the default background-color of #rgb*/	50% {
            background-color: #06F;
     /*blue*/
        }

        100% {
            background-color: #F00;
     /*red*/
        }
    }

    .table-text {
        max-height: 60px;
        word-wrap: break-word;
        word-break: break-all;
        overflow:hidden;
    }

    .editable-submit {
        padding: 4px 8.5px !important;
    }

    .editable-cancel {
        padding: 5px 10px !important;
    }

    .td-light {
        background: linear-gradient(to top right, #e43138, #fefefd);
    }

    .datepicker-days>.table-condensed>tbody>tr>td{
        padding: 2px!important;
    }

    div.editable-input > div.editable-date.well > div > div.datepicker-days > table > tbody > tr >td {
        background-color: transparent!important;
    }

    .datepicker-inline {
        width: 190px!important;
    }

    @media screen and (min-width:750px) and (max-width:900px){
        label#date-label{
            font-size: 3px;
            line-height: 12px;
            width: 40px!important;
        }

        label[for=id_delay-selectized]{
            font-size: 3px;
            line-height: 12px;
            width: 20px!important;
        }
    }
</style>
{% endblock %}

{% block breadcrumb %}
    <h1>快速新增</h1>
    <ol class="breadcrumb">
        <li><a href="javascript:void(0);"><i class="fa fa-dashboard"></i> 仪表盘</a></li>
        <li><a href="javascript:void(0);"> 项目管理</a></li>
        <li><a href="javascript:void(0);"> 测试跟踪管理</a></li>
    </ol>
{% endblock %}

{% block content %}

    <div class="row">
         <div class="col-md-12 col-xs-12" style="border-color: #c7c7c7; border-width: 0 0 1px 0; border-style: solid; margin-bottom: 5px;">
             <div class="form-group col-md-6 col-sm-6 col-xs-12">
                 <label class="control-label" id="date-label" style="float: left; width: 70px; margin-top:5px;">上线时间：</label>
                 <div class="input-group col-xs-9">
                    <input type="text" class="input-sm form-control" name="product_date_start" id="id_product_date_group_start" placeholder="开始时间"/>
                    <span class="input-group-addon">to</span>
                    <input type="text" class="input-sm form-control" name="product_date_end" id="id_product_date_group_end" placeholder="结束时间"/>
                 </div>
             </div>
             <div class="form-group col-md-5 col-sm-4 col-xs-12" style="margin-bottom: 5px;">
                 <label class="control-label" for="id_delay" style="float: left; width: 40px; margin-top: 5px;">状态: </label>
                 <div class="col-xs-10" style="margin-left: -13px; margin-top: -3px;">
                     <select name="delay" id="id_delay">
                        <option value="0">按时</option>
                        <option value="1">待定</option>
                        <option value="2">全部</option>
                     </select>
                </div>
             </div>
             <div class="col-md-1 col-sm-2 col-xs-12" style="float: right; margin-bottom: 10px;">
                 <a onclick="javascript:if(timeDifference()){$('#appinventory-list-table').bootstrapTable('refresh')};" id="searchall" class="btn btn-primary btn-sm" style="float: left; padding-top: 5px; padding-bottom: 5px; min-width: 70px;width: 85%;"><i class="fa fa-search"></i>查 询</a>
             </div>
         </div>
        {% verbatim %}
        <div id="appinventory-list">
            <div class="col-md-6">
                <div id="toolbar" class="btn-group">
                    <a id="btn_add" class="btn btn-default" v-if="group_id==0" v-on:click="toAddExpand();">
                        <span class="glyphicon glyphicon-plus"></span>新增
                    </a>
                    <a id="btn_update" class="btn btn-default" v-if="selected<2" @click="toUpdateExpand();">
                        <span class="fa fa-edit"></span>查看/编辑
                    </a>
                    <a id="btn_delete" class="btn btn-default" v-if="selected==1&&group_id==0" @click="delete_inventory()">
                        <span class="fa fa-trash-o"></span>删除
                    </a>
                    <a id="btn_delete_all" class="btn btn-default" v-if="selected>1&&group_id==0" @click="delete_inventory()">
                        <span class="fa fa-trash-o"></span>批量删除
                    </a>
                    <a id="btn_recovery" class="btn btn-default" @click="toRecovery()">
                        <span class="fa fa-square-o"></span>{{ recovery_text }}
                    </a>
                    <a class="btn btn-default dropdown-toggle"
                            data-toggle="dropdown">
                        更多 <span class="caret"></span>
                    </a>
                    <ul class="dropdown-menu pull-right">
                        <li v-if="group_id == '0'"><a onclick="batch_modify_modal('product_date');"><i class="fa fa-pencil-square"></i>  批量修改 上线时间</a></li>
                        <!--li v-if="group_id == '0'"><a onclick="batch_modify_modal('deploy');"><i class="fa fa-pencil-square"></i>  批量修改 部署情况</a></li-->
                        <li v-if="group_id == '0'"><a onclick="batch_modify_modal('urgent');"><i class="fa fa-pencil-square"></i>  批量修改 上线单类型</a></li>
                        <li v-if="group_id == '0'"><a onclick="batch_modify_modal('confirmation');"><i class="fa fa-pencil-square"></i>  批量修改 版本库情况</a></li>
                        <li v-if="[0,1].includes(group_id)"><a onclick="batch_modify_modal('process');"><i class="fa fa-pencil-square"></i>  批量修改 测试进度</a></li>
                        <li class="divider"></li>
                        <li><a onclick="batch_inventory_download()"><i class="fa fa-download"></i>  完整测试跟踪单下载</a></li>
                        <li><a onclick="batch_change_download()"><i class="fa fa-download"></i>  二次变更明细下载</a></li>
                    </ul>
                </div>
            </div>
            <div class="col-md-12">
                <table id="appinventory-list-table" :style="table_style"></table>
            </div>
            <div id="add">
                <div class="modal" tabindex="-1" role="dialog" id="addModal">
                  <div class="modal-dialog" style="width: 900px;">
                    <div class="modal-content">
                      <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title" style="text-align: center;">
                            <span v-if="add_type"><i class="fa fa-warning"></i> 新增 </span>
                            <button class="button-shine" id="rgb" @click="view_type=false" v-if="view_type&&[0,1].includes(group_id)" style="float: left; margin-bottom: -5px;"><i class="fa fa-lock"></i>编辑</button>
                            <span v-if="view_type"><i class="fa fa-eye"></i> 详情 </span>
                            <span v-if="!view_type&&!add_type"><i class="fa fa-warning"></i> 编辑 </span>
                        </h4>
                      </div>
                      <div class="modal-body" :style="modal_style">
                         <form v-show="modal_type" class="form-horizontal" role="form">
                             <div v-if="error_message.error" class="alert alert-danger alert-dismissable">
                                 <button type="button" class="close" data-dismiss="alert">×</button>
                                 请修正下面的错误。
                             </div>
                             <div class="form-group">
                                <label class="col-sm-3 control-label" for="id_name"> <span class="asteriskField">*</span>状态 </label>
                                 <div style="margin-top: 2px;">
                                     <div style="float: left; margin: 5px 0 0 15px;"><label>按时</label></div>
                                     <div style="float: left; margin: 0 5px 0 5px;">
                                        <div :class="['dashDiv',{'disabled': view_type||group_id!=0}]">
                                           <span :class="['dashSpan',{'converted': form_detail.delay==1}]" @click="form_detail.delay=(form_detail.delay==0)?1:0;$('#id_product_date input').val('');"></span>
                                        </div>
                                     </div>
                                     <div style="float: left; margin-top: 5px;"><label>待定</label></div>
                                 </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.name}]">
                                <label class="col-sm-3 control-label" for="id_name"> <span class="asteriskField">*</span>上线单名称 </label>
                                <div class="col-sm-9">
                                     <input type="text" id="id_name" class="form-control" name="inventory_name" v-model="form_detail.name" style="width: 90%;" :disabled="view_type||group_id!=0">
                                     <div v-if="error_message.message.name" class="help-inline error-text">{{ error_message.message.name[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.department}]">
                                 <label class="col-sm-3 control-label" for="id_department"> <span class="asteriskField">*</span>提出部门 </label>
                                 <div :class="['col-sm-9',{'disabled': view_type||group_id!=0}]">
                                     <select name="department" id="id_department" style="width: 90%;" data-placeholder="请选择提出部门"></select>
                                     <div v-if="error_message.message.department" class="help-inline error-text">{{ error_message.message.department[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.system}]">
                                 <label class="col-sm-3 control-label" for="id_system"> <span class="asteriskField">*</span>系统 </label>
                                 <div :class="['col-sm-9',{'disabled': view_type||group_id!=0}]">
                                     <select name="system" id="id_system" style="width: 90%;" data-placeholder="请选择系统"></select>
                                     <div v-if="error_message.message.system" class="help-inline error-text">{{ error_message.message.system[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.submitter}]">
                                <label class="col-sm-3 control-label" for="id_submitter">上线单提交人 </label>
                                <div class="col-sm-9">
                                     <input type="text" id="id_submitter" class="form-control" name="submitter" v-model="form_detail.submitter" style="width: 90%;" :disabled="view_type||group_id!=0">
                                     <div v-if="error_message.message.submitter" class="help-inline error-text">{{ error_message.message.submitter[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.checker}]">
                                <label class="col-sm-3 control-label" for="id_checker">复核人 </label>
                                <div class="col-sm-9">
                                     <input type="text" id="id_checker" class="form-control" name="checker" v-model="form_detail.checker" style="width: 90%;" :disabled="view_type||group_id!=0">
                                     <div v-if="error_message.message.checker" class="help-inline error-text">{{ error_message.message.checker[0] }}</div>
                                </div>
                             </div>

                             <div class="form-group" style="margin-top: -5px;">
                                <label class="col-sm-3 control-label" for="id_content">内容 </label>
                                <div class="col-sm-9">
                                    <div class="form-control-static form-static-text" id="id_release_name" style="width: 90%; margin-bottom:-13px; white-space: pre-wrap;" v-if="view_type||group_id!=0" v-html="form_detail.content"></div>
                                     <textarea class="form-control" id="id_content" rows="3" v-model="form_detail.content" style="width: 90%; margin-top: 9px;" v-else></textarea>
                                </div>
                             </div>

                             <div class="form-group" style="margin-top: -5px;">
                                <label class="col-sm-3 control-label" for="id_trade">涉及交易 </label>
                                <div class="col-sm-9">
                                    <div class="form-control-static form-static-text" id="id_release_name" style="width: 90%; margin-bottom:-13px; white-space: pre-wrap;" v-if="view_type||group_id!=0" v-html="form_detail.trade"></div>
                                     <textarea class="form-control" id="id_trade" rows="3" v-model="form_detail.trade" style="width: 90%; margin-top: 9px;" v-else></textarea>
                                </div>
                             </div>

                             <!--div v-bind:class="['form-group',{'has-error':error_message.message.deploy}]">
                                <label class="col-sm-3 control-label" for="id_deploy"><span class="asteriskField">*</span>部署情况 </label>
                                <div class="col-sm-9">
                                    <label class="radio-inline" v-for="(item, index) in deploy_list">
                                        <input type="radio" :value="index" v-model="form_detail.deploy" checked="form_detail.deploy==index" :disabled="view_type||group_id!=0"> {{ item }}
                                    </label>
                                    <div v-if="error_message.message.deploy" class="help-inline error-text">{{ error_message.message.deploy[0] }}</div>
                                </div>
                             </div-->

                             <div class="form-group">
                                <label class="col-sm-3 control-label" for="id_product_date"><span v-if="form_detail.delay=='0'" class="asteriskField">*</span>上线时间 </label>
                                <div class="col-sm-9">
                                     <div class="input-group date" id="id_product_date" style="width: 90%;">
                                          <input type="text" class="form-control" :disabled="form_detail.delay==1||view_type||group_id!=0"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
                                     </div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.urgent}]">
                                <label class="col-sm-3 control-label" for="id_urgent"><span class="asteriskField">*</span>上线单类型 </label>
                                <div class="col-sm-9">
                                    <label class="radio-inline" v-for="(item, index) in urgent_list">
                                        <input type="radio" :value="index" v-model="form_detail.urgent" checked="form_detail.urgent==index" :disabled="view_type||group_id!=0"> {{ item }}
                                    </label>
                                    <div v-if="error_message.message.urgent" class="help-inline error-text">{{ error_message.message.urgent[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.trade_method}]">
                                <label class="col-sm-3 control-label" for="id_trade_method"><span class="asteriskField">*</span>验证方式 </label>
                                <div class="col-sm-9">
                                    <label class="radio-inline" v-for="(item, index) in trade_method_list">
                                        <input type="radio" :value="index" v-model="form_detail.trade_method" checked="form_detail.trade_method==index" :disabled="view_type||group_id!=0"> {{ item }}
                                    </label>
                                    <div v-if="error_message.message.trade_method" class="help-inline error-text">{{ error_message.message.trade_method[0] }}</div>
                                </div>
                             </div>

                             <div v-if="trade_content_selected" class="form-group" style="margin-top: -5px;">
                                <label class="col-sm-3 control-label" for="id_trade_content">验证交易 </label>
                                <div class="col-sm-9">
                                    <div class="form-control-static form-static-text" id="id_trade_content" style="width: 90%; margin-bottom:-13px; white-space: pre-wrap;" v-if="view_type||group_id!=0" v-html="form_detail.trade_content"></div>
                                     <textarea class="form-control" id="id_content" rows="3" v-model="form_detail.trade_content" style="width: 90%; margin-top: 9px;" v-else></textarea>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.confirmation}]">
                                <label class="col-sm-3 control-label" for="id_confirmation"><span class="asteriskField">*</span>版本库情况 </label>
                                <div class="col-sm-9">
                                    <label class="radio-inline" v-for="(item, index) in confirmation_list">
                                        <input type="radio" :value="index" v-model="form_detail.confirmation" checked="form_detail.confirmation==index" :disabled="view_type||group_id!=0"> {{ item }}
                                    </label>
                                    <div v-if="error_message.message.confirmation" class="help-inline error-text">{{ error_message.message.confirmation[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.version}]">
                                <label class="col-sm-3 control-label" for="id_version">变更单版本编号 </label>
                                <div class="col-sm-9">
                                     <input type="text" id="id_version" class="form-control" name="version" v-model="form_detail.version" style="width: 90%;" :disabled="view_type">
                                     <div v-if="error_message.message.version" class="help-inline error-text">{{ error_message.message.version[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.product_no}]">
                                <label class="col-sm-3 control-label" for="id_product_no">运维变更单号 </label>
                                <div class="col-sm-9">
                                     <input type="text" id="id_product_no" class="form-control" name="product_no" v-model="form_detail.product_no" style="width: 90%;" :disabled="view_type">
                                     <div v-if="error_message.message.product_no" class="help-inline error-text">{{ error_message.message.product_no[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.tester}]">
                                <label class="col-sm-3 control-label" for="id_tester">测试人员 </label>
                                <div class="col-sm-9">
                                     <input type="text" id="id_tester" class="form-control" name="tester" v-model="form_detail.tester" style="width: 90%;" :disabled="view_type">
                                     <div v-if="error_message.message.tester" class="help-inline error-text">{{ error_message.message.tester[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.process}]">
                                <label class="col-sm-3 control-label" for="id_process"><span class="asteriskField">*</span>测试进度 </label>
                                <div class="col-sm-9">
                                    <label class="radio-inline" v-for="(item, index) in process_list">
                                        <input type="radio" :value="index" v-model="form_detail.process" checked="form_detail.process==index" :disabled="view_type"> {{ item }}
                                    </label>
                                    <div v-if="error_message.message.process" class="help-inline error-text">{{ error_message.message.process[0] }}</div>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.description}]">
                                <label class="col-sm-3 control-label" for="id_description">备注 </label>
                                <div class="col-sm-9">
                                     <input type="text" id="id_description" class="form-control" name="description" v-model="form_detail.description" style="width: 90%;" :disabled="view_type">
                                     <div v-if="error_message.message.description" class="help-inline error-text">{{ error_message.message.description[0] }}</div>
                                </div>
                             </div>

                         </form>

                      </div>
                      <div class="modal-footer" style="margin-top: 3px;">
                          <button class="btn btn-primary" type="submit" id="submit" @click="toAdd()" v-if="!view_type">
                                <i class="fa fa-check"></i>
                                提交
                          </button>
                          <button type="button" class="btn btn-danger" data-dismiss="modal">
                              <i class="glyphicon glyphicon-remove"></i>
                              关闭
                          </button>
                      </div>
                    </div>
                  </div>
                </div>
           </div>

            <div id="change">
                <div class="modal" tabindex="-1" role="dialog" id="addChangeModal">
                  <div class="modal-dialog">
                    <div class="modal-content">
                      <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title" style="text-align: center;">
                            <span v-if="change_type"><i class="fa fa-warning"></i> 登记二次变更 </span>
                            <span v-if="!change_type"><i class="fa fa-warning"></i> 编辑变更理由 </span>
                        </h4>
                      </div>
                      <div class="modal-body">
                         <form v-show="modal_type" class="form-horizontal" role="form">
                             <div v-if="error_message.error" class="alert alert-danger alert-dismissable">
                                 <button type="button" class="close" data-dismiss="alert">×</button>
                                 请修正下面的错误。
                             </div>
                             <input type="text" v-model="change_detail.name_id" style="display: none;">
                              <div class="form-group">
                                <label class="col-sm-3 control-label" for="id_change_name">对应上线单 </label>
                                <div class="col-sm-9">
                                    <p class="form-control-static form-static-text" id="id_change_name" style="width: 90%;">
                                        {{ change_detail.name }}
                                    </p>
                                </div>
                             </div>

                             <div v-bind:class="['form-group',{'has-error':error_message.message.reason}]">
                                <label class="col-sm-3 control-label" for="id_change_reason"> <span class="asteriskField">*</span>变更原因 </label>
                                <div class="col-sm-9">
                                      <textarea class="form-control" id="id_change_reason" rows="5" v-model="change_detail.reason" style="width: 90%; margin-top: 9px;"></textarea>
                                     <div v-if="error_message.message.reason" class="help-inline error-text">{{ error_message.message.reason[0] }}</div>
                                </div>
                             </div>
                         </form>

                      </div>
                      <div class="modal-footer" style="margin-top: 3px;">
                          <button class="btn btn-primary" type="submit" id="submitChange" @click="toAddChange()">
                                <i class="fa fa-check"></i>
                                提交
                          </button>
                          <button type="button" class="btn btn-danger" data-dismiss="modal">
                              <i class="glyphicon glyphicon-remove"></i>
                              关闭
                          </button>
                      </div>
                    </div>
                  </div>
                </div>
           </div>
        </div>
        {% endverbatim %}
    </div>

{% endblock %}
{% block js %}
    <script src="{% static 'js/vue.min.js' %}"></script>
    <script src="{% static 'js/jquery.resizableColumns.min.js' %}"></script>
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script src="{% static 'js/bootstrap-editable.min.js' %}"></script>
    <script src="{% static 'js/bootbox.js' %}"></script>
    <script src="{% static 'js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'js/bootstrap-datepicker.zh-CN.min.js' %}"></script>

    <script src="{% static 'bootstrap-table/js/bootstrap-table.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-editable.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-filter-control.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-resizable.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-multiple-sort.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-multiple-sort-zh-CN.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/tableExport.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-export.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-zh-CN.min.js' %}"></script>

    <script>
            var init_dating = function(){
                var init_date = new Date()
                var day = init_date.getDay() || 7
                var monday = new Date(init_date.getFullYear(), init_date.getMonth(), init_date.getDate() + 1 - day)
                var sunday = new Date(init_date.getFullYear(), init_date.getMonth(), init_date.getDate() + 7 - day)
                return [monday,sunday]
            }

            var init_search = function(){
                var date = init_dating()

                $('#id_product_date_group_start').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true,
                })
                $('#id_product_date_group_end').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true
                })
                $('#id_product_date_group_start').datepicker('setDate', date[0])
                $('#id_product_date_group_end').datepicker('setDate', date[1])

                $('#id_delay').selectize()
            }

            init_search()

            var queryParams = function (params) {
                var ordering
                if(params.sort){
                    switch (params.order)
                    {
                        case 'asc':
                          ordering=params.sort
                          break
                        case 'desc':
                          ordering='-'+params.sort
                          break
                    }
                }else{
                    ordering=''
                }
                var setup = {}
                $('#id_product_date_group_start,#id_product_date_group_end,#id_delay').each(function(i){
                    el = $(this)
                    if(el.val()){
                        setup[el.attr('name')]=el.val()
                    }
                })
                var multiSort=[]
                if(params.multiSort != undefined && !params.sort){
                    params.multiSort.forEach(function(v){
                        switch (v.sortOrder)
                        {
                            case 'asc':
                              multiSort.push({sortName:v.sortName,sortOrder:''})
                              break
                            case 'desc':
                              multiSort.push({sortName:v.sortName,sortOrder:'-'})
                              break
                        }
                    })
                }
                var page = Math.ceil(params.offset / params.limit) + 1 ||1
                var param = {
                    page: page,
                    page_size: params.limit,
                    ordering: ordering,
                    search: params.search,
                    filter: params.filter,
                    setup: JSON.stringify(setup),
                    multiSort: JSON.stringify(multiSort),
                }
                return param
            }

            var responseHandler = function (e) {
                if (e.total > 0) {
                  return { "rows": e.rows, "total": e.total }
                }
                else {
                  return { "rows": [], "total": 0 }
                }
            }

            var delete_item = function(id){
                var res
                $.ajax({
                        type: "post",
                        url: "/project/deleteinventoryinfo/?id="+id,
                        headers: {"X-CSRFtoken": '{{ csrf_token }}'},
                        async: false,
                        success: function (data){
                            res=data
                        }
                    })
                return res
            }

            var delete_inventory = function(){
                var allSelectedData = $('#appinventory-list-table').bootstrapTable('getSelections')
                total = allSelectedData.length
                count = 0
                bootbox.dialog({
                    title : "",
                    message : "<h4 style='text-align:center;'>请确认是否删除相关记录</h4>",
                    buttons : {
                        "success" : {
                            "label" : "<i class='icon-ok'></i> 确认",
                            "className" : "btn-sm btn-success",
                            "callback" : function() {
                                if(total > 0){
                                    for(n in allSelectedData) {
                                        result = delete_item(allSelectedData[n].id)
                                        if (result.message) {
                                            count += 1
                                        }
                                        $('#appinventory-list-table').bootstrapTable('refresh')
                                    }
                                    bootbox.alert('共删除' + count + '条记录')
                                }else{
                                    bootbox.alert('请选择一条记录')
                                }
                            },
                        },
                        "cancel" : {
                            "label" : "<i class='icon-info'></i> 取消",
                            "className" : "btn-sm btn-danger",
                            "callback" : function() { }
                        }
                    }
                });
            }

           var delete_change = function(id){
                bootbox.dialog({
                    title : "",
                    message : "<h4 style='text-align:center;'>请确认是否删除相关记录</h4>",
                    buttons : {
                        "success" : {
                            "label" : "<i class='icon-ok'></i> 确认",
                            "className" : "btn-sm btn-success",
                            "callback" : function() {
                                var res
                                $.ajax({
                                        type: "post",
                                        url: "/project/deletechangeinfo/?id="+id,
                                        headers: {"X-CSRFtoken": '{{ csrf_token }}'},
                                        async: false,
                                        success: function (data){
                                            data.message?bootbox.alert('删除成功!'):bootbox.alert(data.errors)
                                            $('.change-table tr[data-uniqueid="'+id+'"]').parent().parent().bootstrapTable('refresh')
                                        },
                                        error: function (data){
                                            bootbox.alert("后台错误!")
                                            $('#appinventory-list-table').bootstrapTable('refresh')
                                        },
                                    })
                            },
                        },
                        "cancel" : {
                            "label" : "<i class='icon-info'></i> 取消",
                            "className" : "btn-sm btn-danger",
                            "callback" : function() { }
                        }
                    }
                });
            }

            var default_range = function(dt, type){
                    var date = new Date(dt);
                    type=='1'?date.setDate(date.getDate() + 30):date.setDate(date.getDate() - 30)
                    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
                }

            var timeDifference = function (){
                var delay = $('#id_delay').val()
                if(delay=='1'){
                    bootbox.alert('将查询待定上线日期的上线单!')
                    $('#id_product_date_group_start').val("")
                    $('#id_product_date_group_end').val("")
                    return true
                }
                var start = $('#id_product_date_group_start').val()
                var end = $('#id_product_date_group_end').val()
                if(!start&&!end){
                    bootbox.alert('请选择上线时间范围!')
                    return false
                }
                if(!start){
                    $('#id_product_date_group_start').datepicker('setDate',default_range(end,0))
                    return true
                }
                if(!end){
                    $('#id_product_date_group_end').datepicker('setDate',default_range(start,1))
                    return true
                }
                var date = new Date(end).getTime() - new Date(start).getTime()   //时间差的毫秒数
                if(date<0){
                    bootbox.alert('开始时间不能大于结束时间')
                    return false
                }
                var days=Math.floor(date/(24*3600*1000))
                if(days>365){
                    bootbox.alert('搜索范围不能超过365天!')
                    return false
                }
                return true
            }
            
            var tradeMethodItems = { 0: "无需验证", 1: "当晚验证", 2: "次日验证", 3: "首笔验证", 4: "跟随主体"}
            
            var urgentHandle = function (value, row, index) {
                var html = value == '0'?'正常':(value == '1'?'紧急':'灵活')
                return html;
            }

            var deployHandle = function (value, row, index) {
                var html = value == '0'?'<div class="td-light">未部署</div>':(value == '1'?'已部署':'无需部署')
                return html;
            }

            var confirmationHandle = function (value, row, index) {
                var html = value == '0'?'无代码':(value == '1'?'<div class="td-light">版本未上</div>':'版本已上')
                return html;
            }

            var processHandle = function (value, row, index) {
                var html = value == '0'?'<div class="td-light">未完成</div>':(value == '1'?'已完成':'无需测试')
                return html;
            }

            var contentFormatter = function (value, row, index) {//赋予的参数
                return '<div class="table-text">'+row.content+'</div>'
            }
            
            var tradeMethodFormatter = function (value, row, index) {//赋予的参数
                return tradeMethodItems[value]
            }
            
            var tradeContentFormatter = function (value, row, index) {//赋予的参数
                return '<div class="table-text">'+row.trade_content+'</div>'
            }

            var tradeFormatter = function (value, row, index) {//赋予的参数
                return '<div class="table-text">'+row.trade+'</div>'
            }

            var operateFormatter = function (value, row, index) {//赋予的参数
                return '<a id="btn-change-add" class="btn btn-mini" style="padding: 2px;" onclick="javascript:vm.toAddChangeExpand('+row.id+',&apos;'+escape(row.name)+'&apos;);"> <i class="glyphicon glyphicon-pencil"></i></a>'
            }

            var changeFormatter = function (value, row, index) {//赋予的参数
                return [
                    '<div style="width: 180px;"><a id="btn-update" class="btn btn-primary btn-mini" onclick="javascript:vm.toUpdateChangeExpand('+row.id+');"> <i class="fa fa-edit"></i>编辑</a> &nbsp; ' ,
                    '<a class="btn btn-danger btn-mini" id="btn-delete" onclick="javascript:delete_change('+row.id+');"><i class="glyphicon glyphicon-remove"></i>删除</a></div>'
                ].join('');
            }

            var initSubTable = function (index, row, $detail) {
                var nameId = row.id;
                $child_table = $detail.html('<table class="change-table" data-name-id="'+nameId+'"></table>').find('table'); //创建子表
                $child_table.bootstrapTable('destroy').bootstrapTable({
                    url: '/project/getchangeinfo/',//子表的异步加载URL
                    classes: 'table table-bordered table-hover children-table',
                    method: 'get',
                    dataType: "json",
                    contentType: 'application/json,charset=utf-8',
                    search: false,
                    pagination: false,
                    sortable: true,
                    sortName: 'create_time',
                    sortOrder: "desc",
                    queryParams: { nameId: nameId },
                    clickToSelect: true,
                    detailView: false,//父子表
                    uniqueId: "id",
                    columns:
                        [
                            {field: 'reason', title: '变更原因', align:"center",},
                            {field: 'create_time', title: '变更时间', align:"center",width: 180,},
                            {% if perms.projs.admin_appinventory %}{field: 'operate', title: '操作', align: 'center', valign: 'middle', width: 200, formatter: changeFormatter},{% endif %}
                        ],
                })
            };
            
            var confirmationItems = {0:'无代码',1:'版本未上',2:'版本已上'}
            var processItems = {0:'未完成',1:'已完成',2:'无需测试'}
            var deployItems = {0:'未部署',1:'已部署',2:'无需部署'}
            var urgentItems = {0:'正常',1:'紧急',2:'灵活'}
            var inventoryRe = /[\s\"]/
            var tableInit = function (name) {
              $('#appinventory-list-table').empty()
              $('#appinventory-list-table').bootstrapTable('destroy').bootstrapTable({
                  url: '/project/getinventoryinfo/',   //url一般是请求后台的url地址,调用ajax获取数据。此处我用本地的json数据来填充表格。
                  method: "get",                     //使用get请求到服务器获取数据
                  dataType: "json",
                  contentType: 'application/json,charset=utf-8',
                  toolbar: "#toolbar",                //一个jQuery 选择器，指明自定义的toolbar 例如:#toolbar, .toolbar.
                  uniqueId: "id",                    //每一行的唯一标识，一般为主键列
                  cache: false,                       // 不缓存
                  classes: "table table-bordered table-hover table-striped",
                  queryParamsType: "limit",           //设置为"undefined",可以获取pageNumber，pageSize，searchText，sortName，sortOrder
                                                      //设置为"limit",符合 RESTFul 格式的参数,可以获取limit, offset, search, sort, order
                  queryParams: queryParams,
                  sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                  sortable: true,                     //是否启用排序,意味着整个表格都会排序
                  sortName: 'id',                    // 设置默认排序为 name
                  sortOrder: "desc",                   //排序方式
                  pagination: true,                   //是否显示分页（*）
                  search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                  strictSearch: true,
                  showColumns: true,                  //是否显示所有的列
                  showRefresh: true,                  //是否显示刷新按钮
                  showToggle: true,                    //是否显示详细视图和列表视图
                  clickToSelect: true,                //是否启用点击选中行
                  minimumCountColumns: 3,          //最少允许的列数 clickToSelect: true, //是否启用点击选中行
                  pageNumber: 1,                   //初始化加载第一页，默认第一页
                  pageSize: 10,                    //每页的记录行数（*）
                  pageList: [10,20,50,100,500,'所有'],     //可供选择的每页的行数（*）
                  paginationPreText: "上一页",
                  paginationNextText: "下一页",
                  detailView: true,//父子表
                  resizable: true,
                  filterControl: true,
                  filterShowClear: true,
                  showMultiSort: true,
                  responseHandler: responseHandler,
                  showExport: true,
                  exportDataType: 'selected',
                  exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel',],
                  exportOptions: {
                    ignoreColumn: ['0','operate','create_time'],
                    mso: {
                        worksheetName: '上线单',
                    },
                    onCellHtmlData: function (cell, rowIndex, colIndex, htmlData) {
                      if (cell.is('th')) {
                        return cell.find('.th-inner').text()
                      }
                      return htmlData
                    },
                  },
                  columns: [
                            {
                                checkbox: true,
                                class: 'checkbox-center-middle cell-ignore',
                                align: 'center',
                                valign: 'middle',
                            }, {% if perms.projs.admin_appinventory %}{
                                field: 'operate',
                                title: '',
                                align: 'center',
                                valign: 'middle',
                                width: 40,
                                formatter: operateFormatter,
                                clickToSelect: false,
                            }, {% endif %}{
                                title: '编号',
                                field: 'id',
                                align: 'center',
                                valign: 'middle',
                                width: 50,
                            }, {
                                title: '提出部门',
                                field: 'department',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'input',
                                sortable:true,
                                width: 100,
                            }, {
                                title: '系统',
                                field: 'system',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'input',
                                sortable:true,
                                width: 100,
                            }, {
                                title: '上线单名称',
                                field: 'name',
                                align: 'center',
                                width: 250,
                                sortable:true,
                                valign: 'middle',
                                filterControl: 'input',
                                {% if perms.projs.admin_appinventory %}
                                editable:{
                                    type: 'textarea',
                                    title: '上线单名称',
                                    showbuttons: 'bottom',
                                    icon: '<i class="fa fa-edit"></i>',
                                    icononly: true,
                                    noeditFormatter: function (value,row,index) {
                                        //console.log(row.id,value)
                                        return ['<div><a style="border-bottom: dashed 1px #0088cc;" onclick="vm.toUpdateExpand('+ row.id +')">' + value +' </a><a href="javascript:void(0)"',
                                        ' data-name="name"',
                                        ' data-pk="'+ row.id +'"',
                                        ' data-value="' + value + '"',
                                        '><i class="fa fa-edit"></i></a><div>'
                                        ].join('')
                                    },
                                    validate: function (value) { //字段验证
                                        if (!$.trim(value)) {
                                            return '不能为空!'
                                        }
                                        if (inventoryRe.test($.trim(value))) {
                                            return '含有空格引号等非法符号!'
                                        }
                                        if ($.trim(value).length>255) {
                                            return '输入长度不能超过255个字符串!'
                                        }
                                    },
                                },{% else %}formatter:function (value, row, index) {
                                    return '<div><a style="border-bottom: dashed 1px #0088cc;" onclick="vm.toUpdateExpand('+ row.id +')">' + value +'</a><div>'
                                },{% endif %}
                            }, {
                                title: '上线时间',
                                field: 'product_date',
                                align: 'center',
                                valign: 'middle',
                                width: 100,
                                sortable:true,
                                {% if perms.projs.admin_appinventory %}
                                editable:{
                                    type: 'date',
                                    title: '上线时间,空值表示状态为待定',
                                    showbuttons: 'bottom',
                                    format: 'yyyy-mm-dd',
                                    icon: '<i class="fa fa-edit"></i>',
                                    placement: 'right',
                                    emptytext: "无",
                                    emptyclass: '',
                                    datepicker:{ language:'zh-CN', },
                                    clear: '&times; 清空',
                                },{% endif %}
                                //filterControl: 'datepicker',
                                //filterDatepickerOptions: {clearBtn: true, orientation: "bottom auto","autoclose":true, "format": "yyyy-mm-dd", "todayHighlight": true, "language": "zh-CN",},
                            }, {
                                title: '内容',
                                field: 'content',
                                align: 'center',
                                valign: 'middle',
                                //width: 250,
                                formatter: contentFormatter,
                            }, {
                                title: '涉及交易',
                                field: 'trade',
                                align: 'center',
                                valign: 'middle',
                                //width: 250,
                                formatter: tradeFormatter,
                            }, {
                                title: '上线单类型',
                                field: 'urgent',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'select',
                                filterData: 'var:urgentItems',
                                sortable:true,
                                width: 100,
                                {% if perms.projs.admin_appinventory %}
                                editable:{
                                    type: 'select',
                                    title: '上线单类型',
                                    icon: '<i class="fa fa-edit"></i>',
                                    source: [{ value: 0, text: "正常" }, { value: 1, text: "紧急" }, {value:2,text:"灵活"}],
                                },{% else %}
                                formatter: urgentHandle,
                                {% endif %}
                            }, {
                                title: '验证方式',
                                field: 'trade_method',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'select',
                                filterData: 'var:tradeMethodItems',
                                sortable:true,
                                width: 100,
                                formatter: tradeMethodFormatter,
                            }, {
                                title: '验证交易',
                                field: 'trade_content',
                                align: 'center',
                                valign: 'middle',
                                visible: false,
                                formatter: tradeContentFormatter,
                            }, /*{
                                title: '部署情况',
                                field: 'deploy',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'select',
                                filterData: 'var:deployItems',
                                sortable:true,
                                width: 100,
                                {% if perms.projs.admin_appinventory %}
                                editable:{
                                    type: 'select',
                                    title: '部署情况',
                                    icon: '<i class="fa fa-edit"></i>',
                                    source: [{ value: 0, text: "未部署" }, { value: 1, text: "已部署" }, {value:2,text:"无需部署"}],
                                },{% else %}
                                formatter: deployHandle,
                                {% endif %}
                            }, */{
                                title: '版本库情况',
                                field: 'confirmation',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'select',
                                filterData: 'var:confirmationItems',
                                sortable:true,
                                width: 100,
                                {% if perms.projs.admin_appinventory %}
                                editable:{
                                    type: 'select',
                                    title: '版本库情况',
                                    icon: '<i class="fa fa-edit"></i>',
                                    source: [{ value: 0, text: "无代码" }, { value: 1, text: "版本未上" }, {value:2,text:"版本已上"}],
                                },{% else %}
                                formatter: confirmationHandle,
                                {% endif %}
                            }, {
                                title: '变更单版本编号',
                                field: 'version',
                                align: 'center',
                                valign: 'middle',
                                sortable:true,
                                filterControl: 'input',
                                width: 150,
                                visible: false,
                                {% if perms.projs.admin_appinventory or perms.projs.test_appinventory %}
                                editable:{
                                    type: 'text',
                                    title: '变更单版本编号',
                                    emptytext: "无",
                                    emptyclass: '',
                                    showbuttons: 'bottom',
                                    icon: '<i class="fa fa-edit"></i>',
                                    validate: function (value) { //字段验证
                                        if (inventoryRe.test($.trim(value))) {
                                            return '含有空格引号等非法符号!'
                                        }
                                        if ($.trim(value).length>32) {
                                            return '输入长度不能超过32个字符串!'
                                        }
                                    },
                                },{% endif %}
                            }, {
                                title: '运维变更单号',
                                field: 'product_no',
                                align: 'center',
                                valign: 'middle',
                                sortable:true,
                                filterControl: 'input',
                                width: 150,
                                {% if perms.projs.admin_appinventory or perms.projs.test_appinventory %}
                                editable:{
                                    type: 'text',
                                    title: '运维变更单号',
                                    emptytext: "无",
                                    showbuttons: 'bottom',
                                    emptyclass: '',
                                    icon: '<i class="fa fa-edit"></i>',
                                    validate: function (value) { //字段验证
                                        if (inventoryRe.test($.trim(value))) {
                                            return '含有空格引号等非法符号!'
                                        }
                                        if ($.trim(value).length>32) {
                                            return '输入长度不能超过32个字符串!'
                                        }
                                    },
                                },{% endif %}
                            }, {
                                title: '上线单提交人',
                                field: 'submitter',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'input',
                                sortable:true,
                                width: 100,
                            }, {
                                title: '复核人',
                                field: 'checker',
                                align: 'center',
                                valign: 'middle',
                                sortable:true,
                                width: 100,
                            }, {
                                title: '测试人员',
                                field: 'tester',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'input',
                                sortable:true,
                                width: 100,
                                {% if perms.projs.admin_appinventory or perms.projs.test_appinventory %}
                                editable:{
                                    type: 'text',
                                    title: '测试人员',
                                    emptytext: "无",
                                    emptyclass: '',
                                    showbuttons: 'bottom',
                                    icon: '<i class="fa fa-edit"></i>',
                                    validate: function (value) { //字段验证
                                        if (inventoryRe.test($.trim(value))) {
                                            return '含有空格引号等非法符号!'
                                        }
                                        if ($.trim(value).length>12) {
                                            return '输入长度不能超过12个字符串!'
                                        }
                                    },

                                },{% endif %}
                            }, {
                                title: '测试进度',
                                field: 'process',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'select',
                                filterData: 'var:processItems',
                                sortable:true,
                                width: 100,
                                {% if perms.projs.admin_appinventory or perms.projs.test_appinventory %}
                                editable:{
                                    type: 'select',
                                    title: '测试进度',
                                    icon: '<i class="fa fa-edit"></i>',
                                    source: [{ value: 0, text: "未完成" }, { value: 1, text: "已完成" }, {value:2,text:"无需测试"}],
                                },{% else %}
                                formatter: processHandle,
                                {% endif %}
                            }, {
                                title: '创建时间',
                                align: 'center',
                                valign: 'middle',
                                field: 'create_time',
                                sortable:true,
                                visible: false,
                            }, {
                                title: '备注',
                                align: 'center',
                                valign: 'middle',
                                field: 'description',
                                width: 200,
                                {% if perms.projs.admin_appinventory or perms.projs.test_appinventory %}
                                editable:{
                                    type: 'textarea',
                                    title: '备注',
                                    emptytext: "无",
                                    emptyclass: '',
                                    icon: '<i class="fa fa-edit"></i>',
                                    showbuttons: 'bottom',
                                    validate: function (value) { //字段验证
                                        if (inventoryRe.test($.trim(value))) {
                                            return '含有空格引号等非法符号!'
                                        }
                                        if ($.trim(value).length>128) {
                                            return '输入长度不能超过128个字符串!'
                                        }
                                    },
                                },{% endif %}
                            }
                      ],
                  onLoadSuccess: function (data) { //加载成功时执行
                      document.documentElement.scrollTop = vm.position
                      $('.editable.editable-click[data-name="urgent"][data-value="1"],.editable.editable-click[data-name="deploy"][data-value="0"],.editable.editable-click[data-name="confirmation"][data-value="1"],.editable.editable-click[data-name="process"][data-value="0"]'){% if perms.projs.admin_appinventory or perms.projs.test_appinventory %}.parent().find('span'){% endif %}.attr('style','background: linear-gradient(to top right, #e43138, #fefefd);')
                  },
                  onLoadError: function (res) { //加载失败时执行
                      console.log(res)
                  },
                  onExpandRow: function (index, row, $detail) {
                      initSubTable(index, row, $detail);
                  },
                  formatAllRows: function() {
                      return '所有'
                  },
                  {% if perms.projs.admin_appinventory or perms.projs.test_appinventory %}
                  onEditableSave: function (field, row, oldValue, $el) {
                      $.ajax({
                            type: "post",
                            url: "/project/getinventoryform/",
                            headers: {"X-CSRFtoken": '{{ csrf_token }}'},
                            data: {field:field,value:$.trim(row[field]),batch:true,id:row.id},
                            dataType: 'JSON',
                            success: function (data) {
                                if(data.errors){bootbox.alert(data.errors)}
                            },
                            error: function () {
                                bootbox.alert("保存失败!")
                            },
                            complete: function () {
                                var p =document.documentElement.scrollTop
                                $('#appinventory-list-table').bootstrapTable('refresh')
                                vm.position = p
                            }
                      })
                },{% endif %}
              });
                 $('#appinventory-list-table').bootstrapTable('hideColumn', 'id')
            }

            var productDateSelect = function(){
                $('#id_product_date').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true
                });
            }

            var systemItems = []
            {% for item in system %}
                systemItems.push({'id':{{item.id}},'title':'{{item.product_name}}'})
            {% endfor %}
            var systemInit = function(){
                var systemSelectize = $('#id_system').selectize({
                        valueField: 'id',
                        labelField: 'title',
                        searchField: 'title',
                    })
                systemSelectize[0].selectize.addOption(systemItems)
            }
            var systemSelect = function(form_detail){
                var systemControl = $('#id_system')[0].selectize
                systemControl.clear()
                for(var i= 0;i<systemItems.length;i++){
                    var systemId = form_detail.system
                    if(systemId == systemItems[i].id){
                        systemControl.addItem(systemId)
                        break
                    }
                }
            }

            var departmentItems = []
            {% for item in department %}
                departmentItems.push({'id':{{item.id}},'title':'{{item.name}}'})
            {% endfor %}
            var departmentInit = function(){
                var departmentSelectize = $('#id_department').selectize({
                        valueField: 'id',
                        labelField: 'title',
                        searchField: 'title',
                    })
                departmentSelectize[0].selectize.addOption(departmentItems)
            }
            var departmentSelect = function(form_detail){
                var departmentControl = $('#id_department')[0].selectize
                departmentControl.clear()
                for(var i= 0;i<departmentItems.length;i++){
                    var departmentId = form_detail.department
                    if(departmentId == departmentItems[i].id){
                        departmentControl.addItem(departmentId)
                        break
                    }
                }
            }

            var initDetail = {'department':'','confirmation':'1','system':'',tester:'','version':'','name':'','product_date':'','content':'','product_no':'','submitter':'','checker':'','trade':'','process':'0','deploy':'0','description':'','delay':'0','urgent':'0','trade_method': '0','trade_content':''}
            var initChange = {'name_id':'','reason':'测试缺陷','name':''}
            var group = {% if perms.projs.admin_appinventory %}0{% elif perms.projs.test_appinventory %}1{% else %}2{% endif %}
            var initTableWidth = $(window).width()-100>1400?$(window).width()-100:1400
            var vm = new Vue({
                el: '#appinventory-list',
                data: {
                    form_detail: $.extend({},initDetail),
                    modal_type: false,
                    error_message: {'error':false,'message':''},
                    selected: 0,
                    confirmation_list: ['无代码', '版本未上', '版本已上'],
                    process_list: ['未完成', '已完成'],
                    deploy_list: ['未部署', '已部署', '无需部署'],
                    urgent_list: ['正常', '紧急','灵活'],
                    trade_method_list: ["无需验证", "当晚验证", "次日验证", "首笔验证", "跟随主体"],
                    add_type: false,
                    view_type: false,
                    change_type: false,
                    modal_style: {height: window.innerHeight-180+'px', overflow: 'auto',},
                    table_style: {width: initTableWidth+'px', margin: "0 auto",},
                    change_detail: $.extend({},initChange),
                    recovery_type: false,
                    group_id: group,
                    position: 0,
                 },
                mounted:function() {
                    tableInit()
                    departmentInit()
                    systemInit()
                    productDateSelect()
                },
                methods: {
                    initForm: function(){
                        var self = this
                        departmentSelect(self.form_detail)
                        systemSelect(self.form_detail)
                        if(self.form_detail.product_date){
                            var convert = new Date(parseInt(self.form_detail.product_date) * 1000)
                            var month = convert.getMonth() + 1
                            $('#id_product_date').datepicker('update', convert.getFullYear()+'-'+month+'-'+convert.getDate())
                        }else {
                            $('#id_product_date').datepicker('update', self.form_detail.product_date)
                        }
                    },
                    toAddExpand: function () {
                        var self = this
                        self.modal_type = true
                        self.add_type = true
                        self.form_detail = $.extend({},initDetail)
                        $('#addModal').modal('show')
                        self.initForm()
                    },
                    toUpdateExpand: function (id) {
                        var self = this
                        id = id!= undefined ?id:0
                        if((self.selected == 1)||id){
                            $.ajax({
                                 url: "/project/getinventoryform/?id="+(id||$('#appinventory-list-table').bootstrapTable('getSelections')[0].id),
                                 type: "get",
                                 dataType: "json",
                                 success: function (data) {
                                     if(data.errors){
                                         bootbox.alert(data.errors)
                                         $('#appinventory-list-table').bootstrapTable('refresh')
                                     } else {
                                         self.modal_type = true
                                         self.view_type = true
                                         self.form_detail = $.extend({},initDetail,JSON.parse(data))
                                         $('#addModal').modal('show')
                                         self.initForm()
                                     }
                                 },
                                 error: function (data) {
                                     bootbox.alert("后台出错!")
                                     $('#appinventory-list-table').bootstrapTable('refresh')
                                 }
                            })
                        } else {
                            bootbox.alert("请选择一条记录!")
                        }
                    },
                    toAdd: function() {
                        var self = this
                        //console.log(this.form_detail)
                        if(self.form_detail.delay == 0 && !$('#id_product_date input').val()){
                            bootbox.alert('上线单状态为正常,上线时间不能为空!')
                            return false
                        }
                        $.ajax({
                             url: "/project/getinventoryform/",
                             headers: {"X-CSRFtoken": '{{ csrf_token }}'},
                             type: "post",
                             data: $.extend({},self.form_detail,{
                                 'department': $('#id_department')[0].selectize.getValue(),
                                 'system': $('#id_system')[0].selectize.getValue(),
                                 'product_date': $('#id_product_date input').val(),
                                 'deploy': '1', //取消编辑部署情况，默认为已部署
                                 'repo':'svn', //预留
                                 'repo_model':'tag' //预留
                             }),
                             dataType: "json",
                        }).done(function(ret){
                             //console.log(ret)
                             self.error_message = {'error':false,'message':''}
                             if (ret.form_errors){
                                 self.error_message = {'error': true, 'message':ret.form_errors}
                             } else{
                                 $('#appinventory-list-table').bootstrapTable('refresh')
                                 self.hideModal()
                                 $('#addModal').modal('hide')
                                 ret.errors?bootbox.alert(ret.errors):bootbox.alert('保存成功!')
                                 self.selected = 0
                             }
                        }).fail(function(ret){
                             self.error_message = {'error':false,'message':''}
                             bootbox.alert("后台出错!")
                        })
                    },
                    hideModal: function() {
                        var self = this
                        self.form_detail = $.extend({},initDetail)
                        self.add_type = false
                        self.error_message = {'error':false,'message':''}
                        self.view_type = false
                        self.modal_type = false
                        self.position = document.documentElement.scrollTop
                     },

                    toAddChangeExpand: function (id, name) {
                        var self = this
                        self.modal_type = true
                        self.change_type = true
                        self.change_detail = $.extend({},initChange,{name_id:id,name: unescape(name)})
                        $('#addChangeModal').modal('show')
                    },
                    toUpdateChangeExpand: function (id) {
                        var self = this
                        $.ajax({
                             url: "/project/getchangeform/?id="+id,
                             type: "get",
                             dataType: "json",
                             success: function (data) {
                                 if(data.errors){
                                     bootbox.alert(data.errors)
                                     $('#appinventory-list-table').bootstrapTable('refresh')
                                 }else{
                                     self.modal_type = true
                                     self.change_detail = $.extend({},initChange,JSON.parse(data))
                                     $('#addChangeModal').modal('show')
                                 }
                             },
                             error: function (data) {
                                 bootbox.alert("后台出错!")
                                 $('#appinventory-list-table').bootstrapTable('refresh')
                             }
                        })
                    },
                    toAddChange: function() {
                        var self = this
                        $.ajax({
                             url: "/project/getchangeform/",
                             headers: {"X-CSRFtoken": '{{ csrf_token }}'},
                             type: "post",
                             data: self.change_detail,
                             dataType: "json",
                        }).done(function(ret){
                             self.error_message = {'error':false,'message':''}
                             if (ret.form_errors){
                                 self.error_message = {'error': true, 'message':ret.form_errors}
                             } else{
                                 ret.errors?bootbox.alert(ret.errors):bootbox.alert('保存成功!')
                                 ret.type?$('#appinventory-list-table').bootstrapTable('refresh'):$('.change-table[data-name-id="'+self.change_detail.name_id+'"]').bootstrapTable('refresh')
                                 self.hideChangeModal()
                                 $('#addChangeModal').modal('hide')
                             }
                        }).fail(function(ret){
                             self.error_message = {'error':false,'message':''}
                             bootbox.alert("后台出错!")
                        })
                    },
                    hideChangeModal: function() {
                        var self = this
                        self.change_detail = $.extend({},initChange)
                        self.change_type = false
                        self.error_message = {'error':false,'message':''}
                        self.modal_type = false
                        self.position = document.documentElement.scrollTop
                     },
                    toRecovery: function() {
                        var self = this
                        var winWidth = $(window).width()-100
                        var minWidth = winWidth>1400?winWidth:1400
                        this.table_style['width'] = self.recovery_type?minWidth + 'px':'2600px'
                        $('#appinventory-list-table').bootstrapTable('showLoading')
                        setTimeout(function(){
                            $('#appinventory-list-table').bootstrapTable('refresh')
                        },1000)
                        self.recovery_type = !self.recovery_type
                    },
                },
                computed: {
                    recovery_text: function(){
                        return !this.recovery_type?'最大化':'最小化'
                    },
                    trade_content_selected: function(){
                        if(this.form_detail.trade_method=='0'){
                            this.form_detail.trade_content=''
                            return false
                        }
                        return true
                    },
                }
             })

            //tableInit();

            $('#addModal').on('hidden.bs.modal', function () {
                vm.hideModal()
            })

            $('#addChangeModal').on('hidden.bs.modal', function () {
                vm.hideChangeModal()
            })

            var checkNum = function(){
                var invSelections = $("#appinventory-list-table").bootstrapTable('getSelections')
                vm.selected = invSelections.length
            }

            $("#appinventory-list-table").on("check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table", function () {
                //点击checkbox触发事件
                checkNum()
            })

            $("#appinventory-list-table").on("refresh.bs.table search.bs.table page-change.bs.table sort.bs.table", function () {
                vm.position=0
                vm.selected=0
            })

            $(window).resize(function() {
                vm.modal_style = {height: window.innerHeight-180+'px', overflow: 'auto',}
            })

            var batch_modify = function(type, value){
                var allSelectedData = $('#appinventory-list-table').bootstrapTable('getSelections')
                total = allSelectedData.length
                count = 0
                if(total > 0){
                    for(n in allSelectedData) {
                        $.ajax({
                                type: "post",
                                url: "/project/getinventoryform/",
                                headers: {"X-CSRFtoken": '{{ csrf_token }}'},
                                async: false,
                                data: {field:type,value:$.trim(value),batch:true,id:allSelectedData[n].id},
                                dataType: 'JSON',
                                success: function (data) {
                                    if(data.message){count += 1}
                                },
                          })
                    }
                    $('#appinventory-list-table').bootstrapTable('refresh')
                    bootbox.alert('共成功修改' + count + '条记录')
                }else{
                    bootbox.alert('请选择一条记录')
                }
            }

            var batch_modify_modal = function(type){
                switch (type)
                    {
                        case 'product_date':
                          bootbox.prompt({
                                title: "批量修改 上线时间(不能为空)",
                                inputType: 'date',
                                buttons: {
                                    confirm: {
                                        label: '确认',
                                        className: 'btn-primary',
                                    },
                                    cancel: {
                                        label: '取消',
                                        className: 'btn-danger',
                                    }
                                },
                                callback: function (result) {
                                    if (result == '') {bootbox.alert('请输入合格的日期格式!')}
                                    else if (result != null) {batch_modify('product_date', result)}
                                }
                            })
                          break
                        case 'deploy':
                          bootbox.prompt({
                                title: "批量修改 部署情况",
                                inputType: 'select',
                                buttons: {
                                    confirm: {
                                        label: '确认',
                                        className: 'btn-primary'
                                    },
                                    cancel: {
                                        label: '取消',
                                        className: 'btn-danger'
                                    }
                                },
                                inputOptions: [
                                    {
                                        text: '未部署',
                                        value: '0',
                                    },
                                    {
                                        text: '已部署',
                                        value: '1',
                                    },
                                    {
                                        text: '无需部署',
                                        value: '2',
                                    }
                                ],
                                callback: function (result) {
                                    if (result != null) {batch_modify('deploy', result)}
                                }
                            })
                          break
                        case 'urgent':
                          bootbox.prompt({
                                title: "批量修改 上线单类型",
                                inputType: 'select',
                                buttons: {
                                    confirm: {
                                        label: '确认',
                                        className: 'btn-primary'
                                    },
                                    cancel: {
                                        label: '取消',
                                        className: 'btn-danger'
                                    }
                                },
                                inputOptions: [
                                    {
                                        text: '正常',
                                        value: '0',
                                    },
                                    {
                                        text: '紧急',
                                        value: '1',
                                    },
                                    {
                                        text: '灵活',
                                        value: '2',
                                    }
                                ],
                                callback: function (result) {
                                    if (result != null) {batch_modify('urgent', result)}
                                }
                            })
                          break
                        case 'confirmation':
                          bootbox.prompt({
                                title: "批量修改 版本库情况",
                                inputType: 'select',
                                inputOptions: [
                                    {
                                        text: '无代码',
                                        value: '0',
                                    },
                                    {
                                        text: '版本未上',
                                        value: '1',
                                    },
                                    {
                                        text: '版本已上',
                                        value: '2',
                                    }
                                ],
                                buttons: {
                                    confirm: {
                                        label: '确认',
                                        className: 'btn-primary'
                                    },
                                    cancel: {
                                        label: '取消',
                                        className: 'btn-danger'
                                    }
                                },
                                callback: function (result) {
                                    if (result != null) {batch_modify('confirmation', result)}
                                }
                            })
                          break
                        case 'process':
                          bootbox.prompt({
                                title: "批量修改 测试进度",
                                inputType: 'select',
                                inputOptions: [
                                    {
                                        text: '未完成',
                                        value: '0',
                                    },
                                    {
                                        text: '已完成',
                                        value: '1',
                                    },
                                    {
                                        text: '无需测试',
                                        value: '2',
                                    }
                                ],
                                buttons: {
                                    confirm: {
                                        label: '确认',
                                        className: 'btn-primary'
                                    },
                                    cancel: {
                                        label: '取消',
                                        className: 'btn-danger'
                                    }
                                },
                                callback: function (result) {
                                    if (result != null) {batch_modify('process', result)}
                                }
                            })
                          break
                    }
            }

            var batch_change_download = function(){
                bootbox.dialog({
                    title : "请选择下载的时间段",
                    message : '<div class="form-group" style="margin-top: 20px;"> <label class="control-label" style="float: left; width: 70px; margin-top:3px;">变更时间：</label> <div class="input-group"> <input type="text" class="input-sm form-control" name="change_date_start" id="id_change_date_group_start" placeholder="开始时间"/> <span class="input-group-addon">to</span> <input type="text" class="input-sm form-control" name="change_date_end" id="id_change_date_group_end" placeholder="结束时间"/> </div> </div>',
                    buttons : {
                        "success" : {
                            "label" : "<i class='icon-ok'></i> 下载",
                            "className" : "btn-sm btn-success",
                            "callback" : function() {
                                var start_date = $('#id_change_date_group_start').val()
                                var end_date = $('#id_change_date_group_end').val()
                                if(!start_date){
                                    bootbox.alert("开始时间不能为空")
                                    return false
                                }
                                if(!end_date){
                                    bootbox.alert("结束时间不能为空")
                                    return false
                                }
                                window.location.href=  "/project/downloadchangeinfo/?start_date="+start_date+"&end_date="+end_date
                            },
                        },
                        "cancel" : {
                            "label" : "<i class='icon-info'></i> 取消",
                            "className" : "btn-sm btn-danger",
                            "callback" : function() { }
                        }
                    }
                });
                var date = init_dating()

                $('#id_change_date_group_start').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true,
                })
                $('#id_change_date_group_end').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true
                })
                $('#id_change_date_group_start').datepicker('setDate', date[0])
                $('#id_change_date_group_end').datepicker('setDate', date[1])
            }

           var batch_inventory_download = function(){
                bootbox.dialog({
                    title : "请选择下载的时间段",
                    message : '<div class="form-group" style="margin-top: 20px;"> <label class="control-label" style="float: left; width: 70px; margin-top:3px;">上线日期：</label> <div class="input-group"> <input type="text" class="input-sm form-control" name="release_date_start" id="id_inventory_date_batch_start" placeholder="开始时间"/> <span class="input-group-addon">to</span> <input type="text" class="input-sm form-control" name="release_date_end" id="id_inventory_date_batch_end" placeholder="结束时间"/> </div> </div>',
                    buttons : {
                        "success" : {
                            "label" : "<i class='icon-ok'></i> 下载",
                            "className" : "btn-sm btn-success",
                            "callback" : function() {
                                var start_date = $('#id_inventory_date_batch_start').val()
                                var end_date = $('#id_inventory_date_batch_end').val()
                                if(!start_date){
                                    bootbox.alert("开始时间不能为空")
                                    return false
                                }
                                if(!end_date){
                                    bootbox.alert("结束时间不能为空")
                                    return false
                                }
                                window.location.href=  "/project/downloadinventoryinfo/?start_date="+start_date+"&end_date="+end_date
                            },
                        },
                        "cancel" : {
                            "label" : "<i class='icon-info'></i> 取消",
                            "className" : "btn-sm btn-danger",
                            "callback" : function() { }
                        }
                    }
                });
                var date = init_dating()

                $('#id_inventory_date_batch_start').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true,
                })
                $('#id_inventory_date_batch_end').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true
                })
                $('#id_inventory_date_batch_start').datepicker('setDate', date[0])
                $('#id_inventory_date_batch_end').datepicker('setDate', date[1])
            }

    </script>
{% endblock %}
